Angular / Steps / Step 4: API integration
API
-
Step
Summary
Source: https://github.com/ganatan/angular-httpclient
1. See lazy loading topics
2. create service
ng g s pages/products/items --flat 3. items.service.ts
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs'; const httpOptions = { headers: new HttpHeaders( { 'Content-Type': 'application/json', } ) }; @Injectable({ providedIn: 'root' }) export class ItemsService { constructor(private http: HttpClient) { } getItems(url: string): Observable 4. items.component.ts
service.ts file should be inclueded in component.ts import { Component, OnInit } from '@angular/core'; import { ItemsService } from './items.service'; import { isPlatformBrowser } from '@angular/common'; import { PLATFORM_ID, APP_ID, Inject } from '@angular/core'; @Component({ selector: 'app-items', templateUrl: './items.component.html', styleUrls: ['./items.component.css'] }) export class ItemsComponent implements OnInit { // eslint-disable-next-line @typescript-eslint/no-explicit-any items: any; loaded: boolean; constructor( @Inject(PLATFORM_ID) private platformId: object, @Inject(APP_ID) private appId: string, private ItemsService: ItemsService ) { this.loaded = false; } ngOnInit(): void { this.getUsers(); } getUsers(): void { this.loaded = false; this.ItemsService.getItems('https://jsonplaceholder.typicode.com/users') .subscribe( items => { this.items = items; this.loaded = true; const platform = isPlatformBrowser(this.platformId) ? 'in the browser' : 'on the server'; console.log(`getUsers : Running ${platform} with appId=${this.appId}`); }); } resetUsers(): void { this.items = null; this.loaded = true; } } 5. items.component.html
name username email {{item.name}} {{item.username}} {{item.email}} 6. items.module.ts
service.ts file should be inclueded in module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ItemsComponent } from './items.component'; import { ItemsRoutingModule } from './items-routing.module'; import { ItemsService } from './items.service'; @NgModule({ imports: [ CommonModule, ItemsRoutingModule, ], exports: [ ItemsComponent ], declarations: [ ItemsComponent ], providers: [ItemsService], }) export class ItemsModule { }